package com.book.service.impl;

import com.book.dao.BookMapper;
import com.book.bean.Book;
import com.book.bean.Borrow;
import com.book.service.BookService;
import com.book.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

public class BookServiceImpl implements BookService {
    @Override
    public List<Borrow> borrowList() {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            return mapper.getBorrowList();
        }
    }

    @Override
    public void returnBook(String id) {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            mapper.deleteBorrow(id);
        }
    }

    @Override
    public List<Book> getActiveBookList() {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            return mapper.getBookList();
        }
    }

    @Override
    public void addBorrow(int sid, int bid) {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            mapper.addBorrow(sid, bid);
        }
    }

    @Override
    public Map<Book, Boolean> getBook() {
        List<Book> canBorrowBooks = this.getActiveBookList();
        Map<Book, Boolean> book = new LinkedHashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        List<Book> bookList;
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            bookList = mapper.getBook();
        }
        if (canBorrowBooks.isEmpty()) {
            for (int i = 0; i < bookList.size(); i++) {
                book.put(bookList.get(i), true);
            }
            return book;
        }
        for (int j = 0; j < bookList.size(); j++) {
            book.put(bookList.get(j),true);
            list.add(bookList.get(j).getBid());
        }
        int number;
        for (int i = 0; i < canBorrowBooks.size(); i++) {
                if ( (number = list.indexOf(canBorrowBooks.get(i).getBid())) > 0) {
                    book.put(bookList.get(number), false);
                }

        }

        return book;
    }

    @Override
    public void deleteBook(int bid) {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            mapper.deleteBook(bid);
        }
    }

    @Override
    public void addBook(String title, String desc, double price) {
        try (SqlSession session = MybatisUtil.getSqlSession()) {
            BookMapper mapper = session.getMapper(BookMapper.class);
            mapper.addBook(title, desc, price);
        }
    }
}
